<template>
  <div
    class="target-container"
    ref="targetRef"
    @dragover="handleDragOver"
    @drop="handleDrop"
  >
    <!-- <h3>容器 2 (精确定位)</h3> -->
    <!-- 目标元素 -->
    <template v-for="item in items">
      <template v-if="item.type === 'bg-panel'">
        <div class="draggable-panel"></div>
      </template>
      <div
        v-else
        class="draggable-item target-item"
        :style="{
          position: 'absolute',
          left: `${item.x}px`,
          top: `${item.y}px`,
          width: '100px',
          height: '50px',
        }"
        @mousedown="startDrag(item, $event)"
        @touchstart="startDrag(item, $event)"
      >
        {{ item.name }}
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";

// 接收父组件传递的项目列表和添加项目的方法
const props = defineProps({
  items: {
    type: Array,
    required: true,
  },
  onAddItem: {
    type: Function,
    required: true,
  },
  onRemoveItem: {
    type: Function,
    required: true,
  },
});

const targetRef = ref(null);

// 拖拽状态
const isDragging = ref(false);
const draggedItem = ref(null);
const initialX = ref(0);
const initialY = ref(0);
const offsetX = ref(0);
const offsetY = ref(0);

// 拖拽处理函数
const handleDragOver = (e) => {
  e.preventDefault();
  e.dataTransfer.dropEffect = "move";
};

const handleDrop = (e) => {
  e.preventDefault();

  const rect = targetRef.value.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  //   const text = e.dataTransfer.getData("text/plain");
  console.log(e.dataTransfer.getData("application/json"));

  const data = JSON.parse(e.dataTransfer.getData("application/json"));

  // 调用父组件的方法添加新项目
  props.onAddItem({
    id: Date.now(),
    name: data.name || "新项目",
    type: data.type,
    x: x - 50, // 调整为元素中心
    y: y - 25,
  });
};

// 内部拖拽相关函数
const startDrag = (item, e) => {
  e.stopPropagation();

  draggedItem.value = item;

  if (e.type === "mousedown") {
    initialX.value = e.clientX;
    initialY.value = e.clientY;
    window.addEventListener("mousemove", drag);
    window.addEventListener("mouseup", endDrag);
  }

  item.isDragging = true;
  isDragging.value = true;
};

const drag = (e) => {
  if (!draggedItem.value) return;

  e.preventDefault();

  const clientX = e.type === "mousemove" ? e.clientX : e.touches[0].clientX;
  const clientY = e.type === "mousemove" ? e.clientY : e.touches[0].clientY;

  offsetX.value = clientX - initialX.value;
  offsetY.value = clientY - initialY.value;

  draggedItem.value.x += offsetX.value;
  draggedItem.value.y += offsetY.value;

  initialX.value = clientX;
  initialY.value = clientY;
};

const endDrag = (e) => {
  if (!draggedItem.value) return;

  window.removeEventListener("mousemove", drag);
  window.removeEventListener("mouseup", endDrag);

  // 获取容器边界
  const containerRect = targetRef.value.getBoundingClientRect();
  const containerWidth = containerRect.width;
  const containerHeight = containerRect.height;

  // 检查元素是否完全超出容器边界
  const isOutside =
    draggedItem.value.x < 0 ||
    draggedItem.value.y < 0 ||
    draggedItem.value.x + 100 > containerWidth ||
    draggedItem.value.y + 50 > containerHeight;

  // 如果元素完全超出边界，则删除它
  if (isOutside) {
    props.onRemoveItem(draggedItem.value.id);
  } else {
    // 否则保留元素并移除拖拽样式
    draggedItem.value.isDragging = false;
  }

  draggedItem.value = null;
  isDragging.value = false;
};

// 初始化
onMounted(() => {
  targetRef.value.style.userSelect = "none";
});
</script>

<style scoped lang="scss">
.target-container {
  flex: 1;
  height: 100%;
  border: 1px solid #ddd;

  border-radius: 4px;
  position: relative;
  .draggable-panel {
    width: 100%;
    height: 100%;
    position: relative;
    background-color: $color_1;
  }
  .draggable-item {
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    padding: 10px;
    margin: 5px;
    border-radius: 4px;
    cursor: move;
    user-select: none;
    text-align: center;
  }

  .target-item {
    background-color: #e6f7ff;
    border-color: #91d5ff;
  }

  /* 拖拽时的样式 */
  .target-item[style*="dragging"] {
    opacity: 0.8;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    z-index: 10;
  }
}
</style>
